package com.bjc.service.impl;

import com.bjc.dao.TxLogDao;
import com.bjc.domain.Order;
import com.bjc.domain.TxLog;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

/**
 * @program: spring-cloud-alibaba
 * @description:
 * @author: bjc
 * @create: 2021-08-08 21:23
 */
@Service
@RocketMQTransactionListener(txProducerGroup = "tx_producer_group")
public class OrderTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private OrderTransaction orderTransaction;

    @Autowired
    private TxLogDao txLogDao;

    //执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        String txId = (String) message.getHeaders().get("txId");
        try {
            //本地事务
            Order order = (Order) o;
            orderTransaction.createOrder(txId,order);
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    //消息回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String txId = (String) message.getHeaders().get("txId");
        TxLog txLog = txLogDao.findById(txId).get();
        if (txLog!=null){
            //本地事务（订单）成功
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
